﻿using System;
using System.ComponentModel;

namespace VisualWip.Core.Columns
{
    public abstract class Column : ColumnBase
    {
        private readonly BackgroundWorker _backgroundWorker;

        protected Column()
        {
            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += DoBackgroudRefresh;
            _backgroundWorker.RunWorkerCompleted += BackgroundRefreshCompleted;
            _backgroundWorker.ProgressChanged += BackgrounRefreshProgressChanged;
        }

        protected virtual void BackgrounRefreshProgressChanged(object sender, ProgressChangedEventArgs e)
        {
        }

        protected virtual void BackgroundRefreshCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            OnRefreshDone();
        }

        protected virtual void DoBackgroudRefresh(object sender, DoWorkEventArgs e)
        {
            DoRefresh();
        }

        public void Refresh(bool refreshAsync)
        {
            if (_backgroundWorker.IsBusy)
                return;

            OnPreRefresh();
            DoPreRefresh();
            if (refreshAsync)
            {
                _backgroundWorker.RunWorkerAsync();
                OnRefreshing();
            }
            else
            {
                OnRefreshing();
                DoRefresh();
                OnRefreshDone();
            }

        }

        protected virtual void OnRefreshing()
        {
            if (Refreshing != null)
                Refreshing(this, EventArgs.Empty);
        }


        public abstract void DoRefresh();

        protected virtual void DoPreRefresh()
        {
        }

        protected virtual void OnPreRefresh()
        {
            if (PreRefresh != null)
                PreRefresh(this, EventArgs.Empty);
        }

        public event EventHandler RefreshDone;
        public event EventHandler PreRefresh;
        public event EventHandler Refreshing;

        protected virtual void OnRefreshDone()
        {
            if (RefreshDone != null)
                RefreshDone(this, EventArgs.Empty);
        }
    }
}